(function(){
    var that;
    function Game(map){
        
        this.food = new Food();
        this.snake = new Snake();
        this.map = map;
        that = this;
    }

    Game.prototype.start = function (){
        this.food.render(this.map);
        this.snake.render(this.map);
        runSnake();
        bindKey();
        
    }
   //通过键盘按键改变蛇的移动方向
    function bindKey () {
         // 37 - left
         // 38 - top
         // 39 - right
         // 40 - bottom
         document.addEventListener('keydown',function(e){
            switch(e.keyCode){
                case 37 :
                    this.snake.direction = 'left';
                    break;
                case 38 :
                    this.snake.direction = 'top';
                    break;
                case 39 :
                    this.snake.direction = 'right';
                    break;
                case 40 :
                    this.snake.direction = 'bottom';
                    break;
            }
         }.bind(that),false);
    }
    function runSnake(){
        var timer = setInterval(function(){
            this.snake.moveSnake(this.food,this.map);
            this.snake.render(this.map);
            var maxX = this.map.offsetWidth / this.snake.width;
            var maxY = this.map.offsetHeight / this.snake.height;
            var headX = this.snake.body[0].x;
            var headY = this.snake.body[0].y;
            if (headX < 0 || headX >= maxX) {
              alert('Game Over');
              clearInterval(timer);
            }
    
            if (headY < 0 || headY >= maxY) {
              alert('Game Over');
              clearInterval(timer);
            }
        }.bind(that),150);
    }
   //当碰到边界，游戏结束

   //当蛇吃到食物，蛇身加长，食物重新渲染






    window.Game = Game;
    var map = document.getElementById('map');
    var gameSnake = new Game(map);
    gameSnake.start();
})(); 